package com.thinkit.cms.strategy.actuator;

import com.thinkit.cms.strategy.convers.CategoryConvert;
import com.thinkit.cms.strategy.filter.FilterChain;
import com.thinkit.cms.strategy.filter.TmpActuator;
import com.thinkit.core.annotation.Actuator;
import com.thinkit.core.constant.Channel;
import com.thinkit.utils.enums.ActionEnum;
import com.thinkit.utils.enums.ChannelEnum;
import com.thinkit.utils.utils.Checker;
import com.thinkit.utils.utils.SpringContextHolder;
import lombok.Getter;
import lombok.Setter;
import org.quartz.JobExecutionContext;

import java.util.Map;

@Actuator(code ="CATEGORY_PAGE_ACTUATOR",name = "生成栏目分页模板页")
public class CategoryPageActuator extends TmpActuator {

    @Getter
    @Setter
    private Object params;

    @Getter @Setter
    private ActionEnum actionEnum;

    private CategoryConvert categoryConvert;

    public CategoryPageActuator(){
        super();
    }

    public CategoryPageActuator(Object params,ActionEnum actionEnum){
        super();
        this.params = params;
        this.actionEnum =actionEnum;
        this.categoryConvert = SpringContextHolder.getBean(CategoryConvert.class);
    }

    @Override
    public void doFilter(Object params, FilterChain chain) {
        if(Checker.BeNull(params)){
            params = this.params;
        }
        if(Checker.BeNotNull(params)){
            if(ok(params)){
                if(isNotJob()) {
                    String categoryId = categoryConvert.convertParam(params,actionEnum);
                    messageSend.sendMessage(ChannelEnum.CATEGORY_PAGE, Channel.NOTIFY_IT, buildParam(categoryId), true);
                }else{
                    chain.addJobFilter(this);
                }
            }
        }
        chain.doFilter(params,chain);
    }

    private Map<String,Object>  buildParam(String categoryId){
        Map<String,Object> params = categoryService.loadTempParams(categoryId);
        boolean hasDest=params.containsKey(Channel.DEST_PATH) && Checker.BeNotNull(params.get(Channel.DEST_PATH));
        if(hasDest){
            String destPath = params.get(Channel.DEST_PATH).toString();
            if(!destPath.contains(thinkItProperties.getSitePath())){
                String finalDestPath = thinkItProperties.getSitePath()+params.get(Channel.DEST_PATH).toString();
                params.put(Channel.DEST_PATH,finalDestPath);
            }
        }
        return params;
    }



    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext)  {
        Map dateMap = jobExecutionContext.getJobDetail().getJobDataMap();
        messageSend.sendMessage(ChannelEnum.CATEGORY_PAGE, Channel.NOTIFY_IT, dateMap, true);
    }

    public Object getParam(){
        return this.params;
    }

}
